package com.tbflutter.ad_flutter3105;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;

import com.tb.mob.bean.Position;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * AdFlutter3105Plugin
 */
public class AdFlutter3105Plugin implements FlutterPlugin, MethodCallHandler, ActivityAware {

    private static final String CHANNEL = "com.tb.mob";
    private FlutterPluginBinding flutterPluginBinding;

    private MethodChannel channel;

    private Activity activity;

    public static EventChannel.EventSink ee;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        Log.d("____onAttachedToEngine", "________");
        this.flutterPluginBinding = flutterPluginBinding;
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), CHANNEL);
        channel.setMethodCallHandler(this);
        initEventChannel();
    }

    private void initEventChannel() {
        Log.d("____initEventChannel", "________");
        EventChannel eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), CHANNEL + "/event_");
        eventChannel.setStreamHandler(new EventChannel.StreamHandler() {
            @Override
            public void onListen(Object arguments, EventChannel.EventSink events) {
                Log.d("____initEventChannel", "onListen");
                ee = events;
            }

            @Override
            public void onCancel(Object arguments) {
                Log.d("____initEventChannel", "onCancel");
            }
        });
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        Log.d("____onMethodCall", "________");
        eventChannel(call);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        Log.d("onDetachedFromEngine", "________");
        if (channel != null) {
            channel.setMethodCallHandler(null);
        }
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        Log.d("onAttachedToActivity", "________");
        activity = binding.getActivity();
        com.tb.flutter_ad.view.FeedViewFlutterPlugin.registerWith(activity, flutterPluginBinding);
        com.tb.flutter_ad.view.BannerViewFlutterPlugin.registerWith(activity, flutterPluginBinding);
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

    }

    @Override
    public void onDetachedFromActivity() {

    }

    private void eventChannel(MethodCall call) {
        java.util.Map<String, Object> map = com.ads.admob.utils.ValueUtils.getValue(call.arguments, new java.util.HashMap<>());
        if (map == null || map.isEmpty()) {
            return;
        }
        if (call.method.equals("init")) {
            init(map);
            return;
        }
        Log.d("eventChannel____initEE", call.method);


        if (call.method.equals("requestPermission")) {
            RequestPermissionIfNecessary();
            return;
        }
        String codeId = com.ads.admob.utils.ValueUtils.getString(map.get("codeId"));
        if (call.method.equals("loadVideo")) {
            Intent intent = new Intent(activity, com.ads.admob.saas.VideoFragmentActivity.class);
            intent.putExtra("codeId", codeId);
            activity.startActivity(intent);
            return;
        }
        if (call.method.equals("loadPlaylet")) {
            Intent intent = new Intent(activity, com.ads.admob.saas.PlayletFragmentActivity.class);
            intent.putExtra("codeId", codeId);
            activity.startActivity(intent);
            return;
        }
        if (ee == null) {
            Log.d("eventChannel____initEE", "ee==null");
        }
        if (call.method.equals("loadSplash")) {
            loadSplash(map, ee);
        }
        if (call.method.equals("loadInteraction")) {
            loadInteraction(map, ee);
        }
        if (call.method.equals("loadRewardVideo")) {
            loadRewardVideo(map, ee);
        }
    }

    private void loadSplash(java.util.Map<String, Object> map, EventChannel.EventSink events) {
        String codeId = com.ads.admob.utils.ValueUtils.getString(map.get("codeId"));
        Dialog dialog = new Dialog(activity, R.style.tb_flutter_TransparentDialogStyle);
        dialog.setContentView(com.ads.admob.R.layout.dialog_fullscreen);
        FrameLayout mContainer = dialog.findViewById(com.ads.admob.R.id.mContainer);
        dialog.show();
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        com.tb.mob.config.TbSplashConfig config = new com.tb.mob.config.TbSplashConfig.Builder()
                .codeId(codeId)
                .container(mContainer)
                .build();
        com.tb.mob.TbManager.loadSplash(config, activity, new com.tb.mob.TbManager.SplashLoadListener() {
            @Override
            public void onFail(String s) {
                Log.d("Splash____onFail", "Splash loadSplash=" + s);
                dialog.dismiss();
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onError");
                result.put("message", s);
                if (events != null) {
                    events.success(result);
                    events.endOfStream();
                }
            }

            @Override
            public void onTick(long l) {

            }

            @Override
            public void onDismiss() {
                Log.d("Splash____onDismiss", "Splash loadSplash");
                dialog.dismiss();
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdClose");
                if (events != null) {
                    events.success(result);
                    events.endOfStream();
                }
            }


            @Override
            public void onExposure(Position position) {
                Log.d("Splash____onExposure", "Splash loadSplash");
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdShow");
                result.put("eCPM", position.getECPM());
                if (events != null) {
                    events.success(result);
                }
            }

            @Override
            public void onClicked() {
                Log.d("Splash____onClicked", "Splash loadSplash");
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdClick");
                if (events != null) {
                    events.success(result);
                }
            }
        });
    }

    private void loadInteraction(java.util.Map<String, Object> map, EventChannel.EventSink events) {
        String codeId = com.ads.admob.utils.ValueUtils.getString(map.get("codeId"));
        WindowManager manager = activity.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        com.tb.mob.config.TbInteractionConfig config = new com.tb.mob.config.TbInteractionConfig.Builder()
                .codeId(codeId)
                .viewWidth(width)
                .build();
        com.tb.mob.TbManager.loadInteraction(config, activity, new com.tb.mob.TbManager.InteractionLoadListener() {
            @Override
            public void onFail(String s) {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onError");
                result.put("message", s);
                if (events != null) {
                    events.success(result);
                    events.endOfStream();
                }
            }

            @Override
            public void onDismiss() {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdClose");
                if (events != null) {
                    events.success(result);
                    events.endOfStream();
                }
            }

            @Override
            public void getSDKID(Integer integer, String s) {

            }

            @Override
            public void onClicked() {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdClick");
                if (events != null) {
                    events.success(result);
                }
            }

            @Override
            public void onExposure(Position position) {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdShow");
                result.put("eCPM", position.getECPM());
                if (events != null) {
                    events.success(result);
                }
            }

            @Override
            public void onVideoReady() {

            }

            @Override
            public void onVideoComplete() {

            }
        });
    }

    private void loadRewardVideo(java.util.Map<String, Object> map, EventChannel.EventSink events) {
        String codeId = com.ads.admob.utils.ValueUtils.getString(map.get("codeId"));
        String userId = com.ads.admob.utils.ValueUtils.getString(map.get("userId"));
        String extra = com.ads.admob.utils.ValueUtils.getString(map.get("extra"));
        com.tb.mob.config.TbRewardVideoConfig config = new com.tb.mob.config.TbRewardVideoConfig.Builder()
                .codeId(codeId)
                .userId(userId)
                .callExtraData(extra)
                .build();
        com.tb.mob.TbManager.loadRewardVideo(config, activity, new com.tb.mob.TbManager.RewardVideoLoadListener() {
            @Override
            public void onFail(String s) {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onError");
                result.put("message", s);
                if (events != null) {
                    events.success(result);
                    events.endOfStream();
                }
            }

            @Override
            public void getSDKID(Integer integer, String s) {

            }

            @Override
            public void onClick() {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdClick");
                if (events != null) {
                    events.success(result);
                }
            }

            @Override
            public void onClose() {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdClose");
                if (events != null) {
                    events.success(result);
                    events.endOfStream();
                }
            }

            @Override
            public void onExposure(String orderNo, Position position) {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onAdShow");
                result.put("orderNo", orderNo);
                result.put("eCPM", position.getECPM());
                if (events != null) {
                    events.success(result);
                }
            }

            @Override
            public void onRewardVideoCached(com.ads.admob.bean.RewardPosition rewardPosition) {

            }

            @Override
            public void onSkippedVideo() {

            }

            @Override
            public void onRewardVerify() {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onReward");
                if (events != null) {
                    events.success(result);
                }
            }
        });
    }

    private void RequestPermissionIfNecessary() {
        Log.d("RequestPermissionIfNece", "________");
        com.tb.mob.utils.RequestPermission.RequestPermissionIfNecessary(activity); //动态权限
    }

    private void init(java.util.Map<String, Object> map) {
        String appId = com.ads.admob.utils.ValueUtils.getString(map.get("codeId"));
        com.tb.mob.config.TbInitConfig config = new com.tb.mob.config.TbInitConfig.Builder()
                .appId(appId)
                .build();
        com.tb.mob.TbManager.init(activity.getApplicationContext(), config, new com.tb.mob.TbManager.IsInitListener() {
            @Override
            public void onFail(String s) {
                Log.d("init____onFail", "init=" + s);
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onFail");
                result.put("message", s);
                new android.os.Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (ee != null) {
                            ee.success(result);
                            ee.endOfStream();
                        }
                    }
                }, 2000);
            }

            @Override
            public void onSuccess() {
                Log.d("init____onSuccess", "init");
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onSuccess");
                new android.os.Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (ee != null) {
                            ee.success(result);
                            ee.endOfStream();
                        }
                    }
                }, 2000);
            }

            @Override
            public void onDpSuccess() {
                Log.d("init____onDpSuccess", "init");
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("event", "onDpSuccess");
            }
        });
    }
}
